//
//  AppDelegate.swift
//  微博
//
//  Created by 武莎莎 on 15/9/3.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit
import AFNetworking

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    
    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
   
        setUpAperance()
        setUpNetwork()
        
         NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchRootViewController:", name: WSSwitchRootViewControllerNotification, object: nil)
        
        window?.rootViewController = defaultRootViewController()
    
        window?.makeKeyAndVisible()
        return true
    }
    // MARK:判断是否是新版本
    private func isNewVersion() ->Bool{
        let currentVersion = Double((NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String))
        let versionKey = "originVersonKey"
        let originVersion = NSUserDefaults.standardUserDefaults().doubleForKey(versionKey)
        print(currentVersion,originVersion)
        // 把当前版本写入沙盒
        NSUserDefaults.standardUserDefaults().setObject(currentVersion, forKey: versionKey)
        return currentVersion > originVersion
    }
    
    func switchRootViewController(notification:NSNotification){
        window?.rootViewController = (notification.object is WSOAuthController) ? WSWelcomeController() : WSMainController()
    }

    private func defaultRootViewController() -> UIViewController{
        // 判断用户是否登录
        if WSUserAccountViewModel.sharedUserAccount.isLogin {
            return isNewVersion() ? WSNewFeatureController():WSWelcomeController()
        }
        return WSMainController()
    }
    // MARK: 设置网络
    private func setUpNetwork(){
        // 显示网络指示器
        // 只能处理AFN的网络请求，数据加载完毕后会自动消失
        AFNetworkActivityIndicatorManager.sharedManager().enabled = true
    
        //设置默认缓存的大小
        NSURLCache.setSharedURLCache(NSURLCache(memoryCapacity:  4*1024*1024, diskCapacity: 20*1024*1024, diskPath: nil))
    }
    //MARK: 设置导航栏字体颜色
    private func setUpAperance(){
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        UITabBar.appearance().tintColor = UIColor.orangeColor()
    }
    // 销毁通知 deinit不用添加func
    deinit {
        // 注销通知，当程序被销毁的时候就会调用，可以省略
        NSNotificationCenter.defaultCenter().removeObserver(self, name: WSSwitchRootViewControllerNotification, object: nil)
    }
}

